<template>
  <!--仓库-->
  <div>
    <BasicForm @register="warehouseRegisterForm">
      <template #warehouseSlot>
        <Button
          class="mr-2"
          type="primary"
          danger
          :disabled="false"
          v-show="deleteFlag"
          @click="deleteWarehouseClick"
          >删除</Button
        >
        <Button class="mr-2" type="primary" :disabled="isHaveValue" @click="checkAccessClick"
          >检查访问权限</Button
        >
        <Button class="mr-2" type="primary" :disabled="isHaveValue" @click="saveClick">保存</Button>
      </template>
      <template #privateKeySlot>
        <Upload name="file" :beforeUpload="upLoadChange">
          <Button>
            <Icon icon="material-symbols:upload" />
            上传文件
          </Button>
        </Upload>
      </template>
    </BasicForm>
  </div>
</template>

<script setup lang="ts">
  //表单注册  仓库
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { Button, Upload } from 'ant-design-vue';
  import { onMounted, ref } from 'vue';
  import { saveWarehouseItem } from '/@/api/thingsborad/settings/model/settingsModel';
  import {
    deleteRepositorySettings,
    editRepositorySettings,
    getCheckAccessSettings,
    getRepositorySettings,
    getSystemParams,
  } from '/@/api/thingsborad/settings/settings';
  import { useMessage } from '/@/hooks/web/useMessage';
  import Icon from '/@/components/Icon/src/Icon.vue';
  let deleteFlag = ref<boolean>(false);
  let repositorySettingsData = ref<any>();
  let upLoadFile = ref<any>();
  let usernamePasswordFlag = ref<boolean>(true);
  let privateKeyPasswordFlag = ref<boolean>(true);
  let isHaveValue = ref<boolean>(true);
  let isSaveFlag = ref<boolean>(false);
  // 生命周期函数
  onMounted(async () => {
    const systemParams = await getSystemParams();
    if (systemParams.hasRepository) {
      isHaveValue.value = false;
      isSaveFlag.value = true;
      try {
        repositorySettingsData.value = await getRepositorySettings();
        // if (repositorySettingsData.value === null) {
        //   return;
        // }
        usernamePasswordFlag.value = !(
          repositorySettingsData.value.username !== null &&
          repositorySettingsData.value.username !== ''
        );
        privateKeyPasswordFlag.value = !(
          repositorySettingsData.value.privateKeyFileName !== null &&
          repositorySettingsData.value.privateKeyFileName !== ''
        );
        await updateSchema([
          {
            field: 'repositoryUri',
            defaultValue: repositorySettingsData.value.repositoryUri,
          },
          {
            field: 'defaultBranch',
            defaultValue: repositorySettingsData.value.defaultBranch,
          },
          {
            field: 'username',
            defaultValue: repositorySettingsData.value.username,
          },
          {
            field: 'readOnly',
            defaultValue: repositorySettingsData.value.readOnly === true ? 'readOnly' : '',
          },
          {
            field: 'showMergeCommits',
            defaultValue:
              repositorySettingsData.value.showMergeCommits === true ? 'showMergeCommits' : '',
          },
          {
            field: 'authMethod',
            defaultValue: repositorySettingsData.value.authMethod,
          },
        ]);
        deleteFlag.value = true;
        // 根据需要处理数据并更新组件状态
      } catch (error) {
        deleteFlag.value = false;
        console.error('获取数据时出错：', error);
        // 处理错误情况
      }
    }
  });
  // 表单内容 仓库
  const warehouseSchemas: FormSchema[] = [
    {
      ifShow: (value) => {
        if ('repositoryUri' in value.model) {
          if (value.model.repositoryUri !== '') {
            isHaveValue.value = false;
          } else {
            isHaveValue.value = true;
          }
        }
        return true;
      },
      field: 'repositoryUri',
      component: 'Input',
      label: '仓库 URL',
      required: true,
      colProps: {
        span: 13,
      },
      componentProps: {
        placeholder: '请输入仓库 URL',
      },
    },
    {
      field: 'defaultBranch',
      component: 'Input',
      label: '默认分支名称',
      defaultValue: 'main',
      colProps: {
        span: 13,
      },
      componentProps: {
        placeholder: '请输入默认分支名称',
      },
    },
    {
      field: 'readOnly',
      component: 'CheckboxGroup',
      label: '',
      colProps: {
        span: 24,
      },
      componentProps: {
        options: [
          {
            label: '只读',
            value: 'readOnly',
          },
        ],
      },
    },
    {
      ifShow: () => {
        return true;
      },
      field: 'showMergeCommits',
      component: 'CheckboxGroup',
      label: '',
      colProps: {
        span: 24,
      },
      componentProps: {
        options: [
          {
            label: '显示合并提交',
            value: 'showMergeCommits',
          },
        ],
      },
    },
    {
      field: 'authMethod',
      component: 'Select',
      label: '身份验证方法',
      required: true,
      colProps: {
        span: 13,
      },
      defaultValue: 'USERNAME_PASSWORD',
      componentProps: {
        options: [
          {
            label: '密码/访问令牌',
            value: 'USERNAME_PASSWORD',
          },
          {
            label: '私钥',
            value: 'PRIVATE_KEY',
          },
        ],
      },
    },
    {
      ifShow: (value) => {
        return value.model.authMethod === 'PRIVATE_KEY';
      },
      field: 'privateKey',
      component: 'Input',
      slot: 'privateKeySlot',
      label: '私钥',
      colProps: {
        span: 13,
      },
    },
    {
      ifShow: () => {
        return !privateKeyPasswordFlag.value;
      },
      field: 'privateKeyPasswordCheck',
      component: 'CheckboxGroup',
      label: '',
      colProps: {
        span: 24,
      },
      componentProps: {
        options: [
          {
            label: '更改口令',
            value: 'privateKey',
          },
        ],
      },
    },
    {
      ifShow: (value) => {
        let privateKeyPasswordToken;
        if (
          value.model.privateKeyPasswordCheck !== undefined &&
          value.model.privateKeyPasswordCheck[0] === 'privateKey'
        ) {
          privateKeyPasswordToken = true;
        }
        return (
          (privateKeyPasswordFlag.value || privateKeyPasswordToken) &&
          value.model.authMethod === 'PRIVATE_KEY'
        );
      },
      field: 'privateKeyPassword',
      component: 'InputPassword',
      label: '口令',
      colProps: {
        span: 13,
      },
      componentProps: {
        placeholder: '请输入口令',
      },
    },
    {
      ifShow: (value) => {
        return value.model.authMethod === 'USERNAME_PASSWORD';
      },
      field: 'username',
      component: 'Input',
      label: '用户名',
      colProps: {
        span: 13,
      },
      componentProps: {
        placeholder: '请输入用户名',
      },
    },
    {
      ifShow: () => {
        return isSaveFlag.value;
      },
      field: 'usernameCheck',
      component: 'CheckboxGroup',
      label: '',
      colProps: {
        span: 24,
      },
      componentProps: {
        options: [
          {
            label: '更改密码/访问令牌',
            value: 'password',
          },
        ],
      },
    },
    {
      ifShow: (value) => {
        let isShowFlag: any;
        if (value.model.authMethod === 'USERNAME_PASSWORD') {
          isShowFlag = true;
        }
        if (value.model.authMethod === 'password' || isSaveFlag.value) {
          isShowFlag = false;
        }
        if (
          value.model.usernameCheck !== undefined &&
          value.model.usernameCheck[0] === 'password'
        ) {
          isShowFlag = true;
        } else {
          isShowFlag = false;
        }
        // // value.model.authMethod === 'USERNAME_PASSWORD'
        // return usernamePasswordFlag.value || passwordAccessToken;
        return isShowFlag;
      },
      field: 'password',
      component: 'InputPassword',
      label: '密码/访问令牌    (GitHub用户必须使用能够对仓库进行写入权限的访问令牌。)',
      colProps: {
        span: 13,
      },
      componentProps: {
        placeholder: '请输入密码',
      },
    },
    {
      field: 'warehouseButton',
      component: 'Input',
      slot: 'warehouseSlot',
      label: '',
      colProps: {
        span: 24,
      },
    },
  ];
  // 表单初始化
  const [
    warehouseRegisterForm,
    { validate, updateSchema, getFieldsValue, resetFields, setFieldsValue },
  ] = useForm({
    layout: 'vertical',
    schemas: warehouseSchemas,
    actionColOptions: {
      span: 24,
    },
    showActionButtonGroup: false,
  });
  const { createMessage, createConfirm } = useMessage();
  const upLoadChange = (file: File) => {
    // 文件读取
    const reader = new FileReader();
    reader.readAsText(file);
    //获取上传数据
    reader.addEventListener('load', () => {
      upLoadFile.value = {
        privateKeyFileName: file.name,
        privateKey: reader.result,
      };
    });
  };
  //删除点击事件
  function deleteWarehouseClick() {
    createConfirm({
      iconType: 'info',
      title: `确定要删除仓库设置吗？`,
      content: '请注意：确认后，仓库设置将被删除，版本控制功能将不可用。',
      onOk: async () => {
        await deleteRepositorySettings();
        resetFields();
      },
    });
  }
  //检查访问权限点击事件
  async function checkAccessClick() {
    try {
      // 表单验证
      await validate();
      //获取表单数据
      let fieldsValue = getFieldsValue();
      //请求参数填充
      let params: saveWarehouseItem = {
        repositoryUri: fieldsValue.repositoryUri,
        defaultBranch: fieldsValue.defaultBranch,
        readOnly: fieldsValue.readOnly === 'readOnly',
        showMergeCommits: fieldsValue.showMergeCommits[0] === 'showMergeCommits',
        authMethod: fieldsValue.authMethod,
        username: fieldsValue.username,
        password: fieldsValue.password,
      };
      await getCheckAccessSettings(params);
      createMessage.success('检查访问权限成功');
      // 根据需要处理数据并更新组件状态
    } catch (error) {
      console.error('获取数据时出错：', error);
      // 处理错误情况
    }
  }
  //保存点击事件
  async function saveClick() {
    try {
      // 表单验证

      //获取表单数据
      let fieldsValue = await validate();

      let params: saveWarehouseItem;
      // 请求参数填充
      if (fieldsValue.authMethod === 'PRIVATE_KEY') {
        params = {
          repositoryUri: fieldsValue.repositoryUri,
          defaultBranch:
            fieldsValue.defaultBranch === undefined ? 'main' : fieldsValue.defaultBranch,
          readOnly: fieldsValue.readOnly === undefined ? false : true,
          showMergeCommits: fieldsValue.showMergeCommits === undefined ? false : true,
          authMethod: fieldsValue.authMethod,
          privateKeyFileName: upLoadFile.value.privateKeyFileName,
          privateKey: upLoadFile.value.privateKey,
          privateKeyPassword: fieldsValue.privateKeyPassword,
        };
      } else {
        params = {
          repositoryUri: fieldsValue.repositoryUri,
          defaultBranch:
            fieldsValue.defaultBranch === undefined ? 'main' : fieldsValue.defaultBranch,
          readOnly: fieldsValue.readOnly === undefined ? false : true,
          showMergeCommits: fieldsValue.showMergeCommits === undefined ? false : true,
          authMethod: fieldsValue.authMethod,
          username: fieldsValue.username === undefined ? null : fieldsValue.username,
          password: fieldsValue.password === undefined ? null : fieldsValue.password,
        };
      }

      await editRepositorySettings(params);
      isSaveFlag.value = true;
      createMessage.success('保存成功');
      setFieldsValue({
        usernameCheck: undefined,
      });

      // 根据需要处理数据并更新组件状态
    } catch (error) {
      console.error('获取数据时出错：', error);
      // 处理错误情况
    }
  }
</script>
